import { createRouter, createWebHistory } from 'vue-router'
// import Home from '../views/User.vue'
import Layout from "../Layout/layout";
import store from '../store';
import axios from '../utils/request';


// 通用路由 —— 不需要设置权限
const routes = [
  {
    path: '/',
    name:'Layout',
    component: Layout,
    meta:{
      path:'/',
      title:'首页',
    },
    children:[
      {
        path:'',
        name:"index",
        component: ()=>import("@/views/index.vue"),
        meta:{
          path:'/',
          title:''
        }
      }
    ]
  },
  {
    path:'/login',
    name:'Login',
    component:()=>import("../views/login.vue")
  },
  {
    path:'/regision',
    name:'regision',
    component:()=>import("@/views/regision.vue")
  },
  {
    path:'/test',
    name:'test',
    component:()=>import("../views/test.vue")
  }
]



const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})




// 全局导航守卫

//是否存在路由
let hasRoute = store.state.menus.hasRoutes

router.beforeResolve((to,from,next) =>{

  // 获取用户本地的token, 如果token不存在则跳转到登录页
  const tokenStr = localStorage.getItem("token");
   
  if (to.path === '/login'){
    return next();
  }else if(to.path === '/regision'){
    return next();
  }else if (!tokenStr) {
    return next('/login');
  }else if(tokenStr && !hasRoute){
    // router.matcher = newRouter(router).matcher
    // console.log("动态获取路由")
    // 获取动态导航栏
    axios.get('/menu/nav',{
      headers:{
      Authorization:localStorage.getItem('token')
    }
    }).then(res =>{
    // console.log("router: ",res.data)
      // 拿到menuList
			store.commit("setMenuList", res.data.data.nav)
      // 拿到用户权限
      store.commit("setPermList", res.data.data.authority)
      res.data.data.nav.forEach(menu => {
        if(menu.component){
          let route = menuToRoute(menu)
						// 把路由添加到路由管理中
						if (route) {
              router.addRoute('Layout',route);
						}
          }
        if (menu.children) {
					menu.children.forEach(e => {
					// 转成路由
					let route = menuToRoute(e)
					// 把路由添加到路由管理中
					if (route) {
						router.addRoute('Layout',route);
					}
				})
        }
			})
			hasRoute = true;
      router.addRoute(
        {
          path: '/:pathMatch(.*)',
          name: 'error',
          component: () => import('@/components/error-page/404.vue'),
          meta: { title: '404' },
        });
			store.commit("changeRouteStatus", hasRoute);
      next({ ...to, replace: true })
      })
  }else{
    next();
  }
})

// 导航转成路由
const menuToRoute = (menu) => {
	if (!menu.component) {
		return null
	}

	let route = {
		name: menu.name,
		path: menu.path,
    component : () => import('@/views' + menu.component +'.vue'),
		meta: {
			title: menu.title,
      path:menu.path
		}
	}
	return route
}

export default router
